package com.dsz.apiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.dsz.apiclientsdk.model.User;
import com.dsz.apiclientsdk.utils.SignUtil;

import java.util.HashMap;

/**
 * @author dushangzhi
 */
public class MyClient {
    private String accessKey;
    private String secretKey;

    private final String GATEWAY_HOST = "http://localhost:8081/api";

    public MyClient(String accessKey, String secretkey) {
        this.accessKey = accessKey;
        this.secretKey = secretkey;
    }

    private HashMap<String, String> getHeaderMap(String body) {
        HashMap<String, String> map = new HashMap<>();
        map.put("accessKey", accessKey);
//        map.put("secretkey", secretkey);
        map.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        map.put("nonce", RandomUtil.randomNumbers(4));
        map.put("body", body);
        map.put("sign", SignUtil.getSign(body, secretKey));
        return map;
    }


    public String testGet(String name) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("name", name);
        String res = HttpUtil.get(GATEWAY_HOST + "/name", hashMap);
        System.out.println(res);
        return res;
    }

    public String testPost(String name) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("name", name);
        String res = HttpUtil.post(GATEWAY_HOST + "/name", hashMap);
        System.out.println(res);
        return res;
    }

    public String testPost2(User user) {
        String jsonStr = JSONUtil.toJsonStr(user);
        HttpResponse httpResponse = HttpRequest.post(GATEWAY_HOST + "/name/post")
                .body(jsonStr)
                .addHeaders(getHeaderMap(jsonStr))
                .execute();
        int status = httpResponse.getStatus();
        System.out.println(status);
        String body = httpResponse.body();
        System.out.println(body);
        return body;
    }
}
